import _ from 'lodash';
import * as api from '@/services/SupplyPlanReportFormMgr';
import * as utils from '../utils/treeUtils';

const Model = {
  namespace: 'SupplyAndMarketingMonthly',
  state: {
    all: [],
    items: [],
    expandedRowKeys: [],
    level: 'project',
  },
  effects: {
    *init({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: { items: [], expandedRowKeys: [] },
      });
      const response = yield call(api.supplyMonthlyDetailReportUsingGET, payload);
      const level = yield select(state => state.SupplyAndMarketingMonthly.level);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        console.log(response);
        const uniqData = _.unionBy(response.data, 'id');
        _.each(uniqData, v => {
          const x = v;
          if (v.name === '旭辉集团') x.name = '全部';
        });
        const all = _.cloneDeep(uniqData);
        const levelTree = utils.levelTree(uniqData, level);
        const expandedRowKeys = utils.getExpandedRowKeys(levelTree);
        const treeData = utils.buildTree(levelTree);
        yield put({
          type: 'save',
          payload: { all, items: treeData, expandedRowKeys },
        });
        if (callback) callback();
      }
    },
    *level({ payload }, { put, select }) {
      const all = yield select(state => state.SupplyAndMarketingMonthly.all);
      const { level } = payload;
      const levelTree = utils.levelTree(all, level);

      const expandedRowKeys = utils.getExpandedRowKeys(levelTree);
      const treeData = utils.buildTree(levelTree);
      yield put({
        type: 'save',
        payload: { level, items: treeData, expandedRowKeys },
      });
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
